<template>
  <div class="grid" style="gap: 12px">
    <GlassCard>
      <el-form label-position="left" label-width="auto" class="ac-compact">
        <el-form-item label="角度 (°)">
          <div class="row-input">
            <el-input-number
              v-model="state.degrees"
              :precision="6"
              :step="0.1"
              :style="{ width: '180px' }"
              controls-position="right"
              @change="onDegreesChange" />
            <el-button
              circle
              text
              size="small"
              @click="copyToClipboard(state.degrees)">
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="弧度 (rad)">
          <div class="row-input">
            <el-input-number
              v-model="state.radians"
              :precision="8"
              :step="0.001"
              :style="{ width: '180px' }"
              controls-position="right"
              @change="onRadiansChange" />
            <el-button
              circle
              text
              size="small"
              @click="copyToClipboard(state.radians)">
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </GlassCard>
  </div>
</template>

<script setup lang="ts">
import { DocumentCopy } from "@element-plus/icons-vue"
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInputNumber,
  ElMessage
} from "element-plus"
import { reactive } from "vue"

// @ts-ignore - SFC default export by Vue plugin
import GlassCard from "./ui/GlassCard.vue"

type LastEdited = "deg" | "rad" | null

const PI = Math.PI
function toRadians(degrees: number): number {
  return degrees * (PI / 180)
}
function toDegrees(radians: number): number {
  return radians * (180 / PI)
}
function roundTo(value: number, places = 8): number {
  const factor = Math.pow(10, places)
  return Math.round((value + Number.EPSILON) * factor) / factor
}

const state = reactive({
  degrees: 180 as number,
  radians: roundTo(PI, 8) as number,
  lastEdited: null as LastEdited
})

function onDegreesChange(val: number | undefined) {
  if (typeof val !== "number" || !isFinite(val)) return
  state.lastEdited = "deg"
  state.radians = roundTo(toRadians(val), 8)
}
function onRadiansChange(val: number | undefined) {
  if (typeof val !== "number" || !isFinite(val)) return
  state.lastEdited = "rad"
  state.degrees = roundTo(toDegrees(val), 6)
}

async function copyToClipboard(value: number) {
  try {
    await navigator.clipboard.writeText(String(value))
    ElMessage.success("已复制")
  } catch (e) {
    ElMessage.error("复制失败")
  }
}
</script>

<style scoped>
.ac-compact :deep(.el-form-item) {
  margin-bottom: 10px;
}
.row-input {
  display: flex;
  align-items: center;
  gap: 8px;
}
.row-input :deep(.el-input-number) {
  flex: none;
}
.row-input .el-button {
  flex: none;
}
</style>
